package com.game.server.system;

import java.util.Collection;
import java.util.HashMap;


import lombok.Getter;

/**
 * @author 
 * 
 */
@Getter
public class AbstractBase {

	protected int id;
	
    protected HashMap<Integer, AbstractClient> clients;

    public AbstractBase(int id) {
        this.id = id;
        clients = new HashMap<Integer, AbstractClient>();
    }

    /**
     * �����û�
     * 
     * @param client
     */
    public boolean addClient(AbstractClient client) {
        if (clients == null) return false;
        synchronized (clients) {
            int userid = client.getUserId();
            AbstractClient client2 = clients.get(userid);
            if (client2 == null) {
                clients.put(client.getUserId(), client);
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * �����û�
     * 
     * @param client
     */
    public AbstractClient removeClient(int id) {
        if (clients == null) return null;
        synchronized (clients) {
            AbstractClient client = clients.get(id);
            if (client != null && client.getSession() != null) {
//                 client.getSession().close(true);
            }
            return clients.remove(id);
//           return null;
        }
    }

    /**
     * ����û��б�
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public Collection<AbstractClient> getClients() {
        synchronized (clients) {
            return ((HashMap<Integer, AbstractClient>) clients.clone()).values();
        }
    }

    /**
     * ��ȡ�������û�����
     * 
     * @return
     */
    public int GetClientCount() {
        if (clients == null) return 0;
        return clients.size();
    }

    /**
     * ��õ����û�
     * 
     * @param userid
     *            �û�ID
     * @return
     */
    public AbstractClient getClient(int userid) {
        // System.out.print("�û���:"+clients.size());
        synchronized (clients) {
            if (clients == null) return null;
            return clients.get(userid);
        }
    }

    /**
     * ��õ����û�
     * 
     * @param sessionid
     *            �û�ID
     * @return
     */
    public AbstractClient getClient(long sessionid) {
        synchronized (clients) {
            if (clients == null) return null;
            for (AbstractClient client : clients.values()) {
                if (sessionid == client.getSessionid()) {
                    return client;
                }
            }
        }
        return null;
    }


}
